import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'

// 创建axios实例
const service: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 10000
})

// request拦截器
service.interceptors.request.use(
    (config) => {
        const token = getToken()
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token
        }
        return config
    },
    (error) => {
        console.log(error)
        Promise.reject(error)
    }
)

// response拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const res = response.data
        if (res.code !== 200) {
            ElMessage({
                message: res.msg || '系统错误',
                type: 'error',
                duration: 5 * 1000
            })

            // 401: 未登录或token过期
            if (res.code === 401) {
                ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const userStore = useUserStore()
                    userStore.logOut().then(() => {
                        location.reload()
                    })
                })
            }
            return Promise.reject(new Error(res.msg || '系统错误'))
        } else {
            return res
        }
    },
    (error) => {
        console.log('err' + error)
        ElMessage({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

// 封装GET请求
const get = (config: AxiosRequestConfig) => {
    return service.request({ ...config, method: 'GET' })
}

// 封装POST请求
const post = (config: AxiosRequestConfig) => {
    return service.request({ ...config, method: 'POST' })
}

// 封装PUT请求
const put = (config: AxiosRequestConfig) => {
    return service.request({ ...config, method: 'PUT' })
}

// 封装DELETE请求
const del = (config: AxiosRequestConfig) => {
    return service.request({ ...config, method: 'DELETE' })
}

export default {
    get,
    post,
    put,
    delete: del
} 